<template>
  <div v-loading="loading" class="page-wrapper">
    <c-card title="用户列表" class="user-list">
      <el-button slot="func" type="primary" size="small" class="item" @click="showAddDlg">添加</el-button>
      <div class="options row">
        <c-search
          v-model="searchText"
          :width="200"
          placeholder="用户名搜索"
          class="item"
          @submit="_getUsers"
        />
      </div>
      <el-table ref="table" :data="userList" stripe style="width: 100%">
        <el-table-column prop="username" label="登录名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="usercode" label="用户名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="clientName" label="公司名称" show-overflow-tooltip></el-table-column>
        <el-table-column label="性别">
          <template v-slot="{ row }">{{ gender[row.gender] }}</template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="flag" label="状态">
          <template v-slot="{row}">{{ row.flag === 1 ? '正常' : '注销' }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button type="text" @click="showEditDlg(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page.sync="page.index"
          :total="page.total"
          @current-change="_getUsers"
        ></el-pagination>
      </div>
    </c-card>
    <c-dlg
      v-if="userInfo"
      :title="(userInfo.pkid ? '编辑' : '添加') + '用户'"
      :visible.sync="dialogVisible"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="userInfo"
        label-width="60px"
        class="demo-ruleForm"
        label-position="top"
        style="width: 100%;"
      >
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="登录名" prop="username">
              <el-input v-model="userInfo.username" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="用户名" prop="usercode">
              <el-input v-model="userInfo.usercode" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="登录密码" :prop="type === 'add' ? 'password' : null">
              <el-input v-model="userInfo.password" size="small" type="password"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="userInfo.gender">
                <el-radio label="0">男</el-radio>
                <el-radio label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="userInfo.mobile" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="联系电话" prop="telephone">
              <el-input v-model="userInfo.telephone" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="用户邮箱" prop="emailaddress">
              <el-input v-model="userInfo.emailaddress" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="userInfo.userType" size="small">
                <el-option v-for="(u,i) in userTypes" :key="i" :value="u" :label="u"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="用户状态" prop="flag">
              <el-select v-model="userInfo.flag" size="small">
                <!---
                <el-option label="正常" :value="0"></el-option>
                <el-option label="注销" :value="1"></el-option>
                --->
                <!-- 焦 -->
                <el-option label="正常" :value="1"></el-option>
                <el-option label="注销" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="公司名称" prop="clientid">
              <el-select v-model="userInfo.clientid" filterable size="small">
                <el-option v-for="c in comList" :key="c.pkid" :value="c.pkid" :label="c.name"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="用户角色" prop="userrole">
              <el-select
                v-model="userRoles"
                multiple
                filterable
                remote
                size="small"
                reserve-keyword
                placeholder="搜索"
                :remote-method="getRoleList"
                :loading="roleLoading"
              >
                <el-option
                  v-for="item in roleList"
                  :key="item.roleid"
                  :label="item.rolename"
                  :value="item.roleid"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item" style="flex: 1">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="userInfo.memo" type="textarea" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="submitForm">提交</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </c-dlg>
  </div>
</template>

<script>
import CCard from "@/components/CCard";
import CSearch from "@/components/CSearch";
import CDlg from "@/components/CDlg";
import md5 from "md5";
import { clone } from "lodash";
import { elIsMobile, elIsPhone } from "@/utils/validate";
import { calcPageNum } from "@/utils";
export default {
  name: "Users",
  components: {
    CCard,
    CSearch,
    CDlg
  },
  data() {
    return {
      loading: false,
      roleLoading: false,
      searchText: "",
      roleText: "",
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      curUserId: {},
      roleList: null,
      userRoles: [],
      userList: null,
      userInfo: null,
      dialogVisible: false,
      gender: ["男", "女"],
      type: null,
      userTypes: ["系统管理员", "运维用户", "大数据用户", "客户用户", "体验用户"],
      rules: {
        username: [
          { required: true, message: "请输入登录名", trigger: "blur" }
        ],
        usercode: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: elIsMobile, trigger: "blur" }
        ],
        telephone: [{ validator: elIsPhone, trigger: "blur" }],
        emailaddress: [
          { type: "email", message: "邮箱地址格式不正确", trigger: "blur" }
        ],
        userType: [
          { required: true, message: "请选择用户类型", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    comList() {
      return this.$store.getters.comList;
    }
  },
  watch: {
    "page.index"(v) {
      const path = this.$route.path;
      this.$router.push(path + "?page=" + v);
    }
  },
  mounted() {
    const h = this.$refs["table"].$el.clientHeight;
    const n = calcPageNum(h);
    this.$set(this.page, "size", n);

    const page = parseInt(this.$route.query.page || 1);
    this.$set(this.page, "index", page);
    this.loading = true;
    this._getUsers().then(() => {
      this.loading = false;
    });
  },
  methods: {
    _getUsers() {
      const params = {
        userName: this.searchText || "",
        rows: this.page.size,
        page: this.page.index
      };
      return this.$axios
        .get("plat/user/queryUsers", { params })
        .then(res => {
          if (res.code === 1) {
            this.userList = res.data.rows;
            this.$set(this.page, "total", res.data.total);
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    getUserRoles(id) {
      const params = { userId: id };
      return this.$axios
        .get("plat/user/queryUserRole", { params })
        .then(res => {
          if (res.code === 1) {
            this.userRoles = res.data.roles.map(e => e.roleid);
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e))
        .finally(() => {
          this.loading = false;
        });
    },
    getRoleList(query) {
      const params = {
        rows: 20,
        page: 1,
        roleName: query || ""
      };
      this.roleLoading = true;
      return this.$axios
        .get("plat/user/queryRoles", { params })
        .then(res => {
          if (res.code === 1) {
            this.roleList = res.data.rows;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e))
        .finally(() => {
          this.roleLoading = false;
        });
    },
    showAddDlg() {
      this.type = "add";
      if (!this.roleList) {
        this.getRoleList();
      }
      if (!this.userInfo || this.userInfo.pkid) {
        this.userInfo = {
          gender: "0",
          userType: "系统管理员",
          flag: 0
        };
        this.userRoles = [];
      }
      this.dialogVisible = true;
    },
    async showEditDlg(u) {
      this.type = "edit";
      if (!this.roleList) {
        this.getRoleList();
      }
      if (u.pkid !== this.curUserId) {
        this.curUserId = u.pkid;
        this.userInfo = clone(u);
        this.getUserRoles(u.pkid);
      }
      this.dialogVisible = true;
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const load = this.$loading();
          this.userInfo.password &&
            (this.userInfo.password = md5(this.userInfo.password));
          return this.$axios
            .post("plat/user/editUser", this.userInfo)
            .then(res => {
              if (res.code === 1) {
                const id = this.userInfo.pkid || res.data.pkid;
                this.saveUserRole(id)
                  .then(() => {
                    load.close();
                    this._getUsers();
                    this.userInfo = {};
                    this.curUserId = null;
                    this.dialogVisible = false;
                  })
                  .catch(e => {
                    load.close();
                    this.$message.error("用户信息保存成功，分配角色失败！");
                  });
              } else {
                throw res.msg;
              }
            })
            .catch(e => {
              this.$message.error(e);
              load.close();
            });
        } else {
          return false;
        }
      });
    },
    saveUserRole(id) {
      const post = {
        userId: id,
        roleids: this.userRoles.join(",")
      };
      return this.$axios
        .post("plat/user/giveRole", post)
        .then(res => {
          if (res.code !== 1) throw res.msg;
        })
        .catch(e => {
          throw e;
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.main-container {
  height: 100%;
}
.options {
  display: flex;
  .item {
    margin-left: 20px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
}
.el-form {
  width: 700px;
}
</style>
